<script setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
const tableData = ref([])
// 分页
const page = ref(1)
const pageSize = ref(10)
const size = 'large'
const count = ref(0)
const dialogTitle = ref('编辑学生信息')
const inputdisabled = ref(false)
const selectStatus = ref([])
const studentForm = ref({
    user_id: '',
    user_name: '',
    user_account: '',
    user_password: '',
    user_price:'',
    user_createTime: '',
})
const dialogVisible = ref(false);
const handleSizeChange = (val) => {
    pageSize.value = val
    getStudentList()
}
const handleCurrentChange = (val) => {
    page.value = val
    getStudentList()
}
// 删除功能
const handleDelete = (index, row) => {
    // 确认对话框
    const confirm = ElMessageBox.confirm('确认删除该学生吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
    confirm.then(() => {
        axios.post('http://localhost:3000/api/deleteStudent', { sid: row.sid }).then(res => {
            ElMessage.success('删除成功')
            getStudentList()
        }).catch(err => {
            ElMessage.error('删除失败' + err)
        })
    }).catch(() => {
        // 取消删除
        ElMessage.info('已取消删除')
    })
}
// 编辑功能
const handleEdit = (index, row) => {
    studentForm.value = row;
    console.log(studentForm.value)
    // 跳转到编辑页面
    dialogVisible.value = true;
    dialogTitle.value = '编辑打手信息'
    inputdisabled.value = true;
}

const getStudentList = () => {
    axios.get('http://localhost:3000/api/getStudent', { params: { page: page.value, pageSize: pageSize.value } }).then(res => {
        tableData.value = res.data
    }).catch(err => {
        ElMessage.error('获取打手列表失败' + err)
    })
    axios.get('http://localhost:3000/api/getStudentCount').then(res => {
        count.value = res.data[0].count
    }).catch(err => {
        ElMessage.error('获取打手数量失败' + err)
    })
}
const handleSubmit = () => {
    if (dialogTitle.value === '添加打手信息') {
        axios.post('http://localhost:3000/api/addStudent', studentForm.value).then(res => {
            ElMessage.success('添加成功')
            dialogVisible.value = false;
            getStudentList()
        }).catch(err => {
            ElMessage.error('添加失败' + err)
        })
    } else {
        axios.post('http://localhost:3000/api/updateStudent', studentForm.value).then(res => {
            ElMessage.success('修改成功')
            dialogVisible.value = false;
            getStudentList()
        }).catch(err => {
            ElMessage.error('修改失败' + err)
        })
    }
}
// 批量删除功能
const handleBatchDelete = () => {
      const ids = selectStatus.value;
      ElMessage.info(`已选择 ${ids.length} 项`+JSON.stringify(ids))
        if (ids.length === 0) {
            ElMessage.error('请先选择打手')
            return;
        }
    // 确认对话框
    const confirm = ElMessageBox.confirm('确认批量删除选中的打手吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
    confirm.then(async () => {
        // 循环删除
     for (let i = 0; i < ids.length; i++) {
       await    axios.post('http://localhost:3000/api/deleteStudent', { sid: ids[i] }).then(res => {
            }).catch(err => {
                ElMessage.error('删除失败' + err)
            })
        }
        ElMessage.success('删除成功')
        getStudentList()
    }).catch(() => {
        // 取消删除
        ElMessage.info('已取消删除')
    })
}
const showAddDialog = () => {
    studentForm.value = {
        sid: 100000 + parseInt(Math.random() * 100000),
        sname: '',
        gender: '',
        telphone: '',
        address: '',
        creatime: ''
    }
    dialogVisible.value = true;
    dialogTitle.value = '添加学生信息'
    inputdisabled.value = true;
}

const handleSelectionChange = (val) => {
    selectStatus.value = val.map(item => item.sid)
    // ElMessage.info(`已选择 ${val.length} 项`+JSON.stringify(selectStatus.value))
}
onMounted(() => {
    getStudentList()
})
</script>

<template>
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{path: '/admin/welcome'}">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
            <a href="/admin/student">打手管理</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>打手列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider />
    <el-card>
        <el-button type="primary" plain @click="showAddDialog()"> <el-icon>
                <Plus />
            </el-icon> 添加打手</el-button>
        <!-- <el-button type="info" plain @click="handleBatchDelete()"> -->
            <!-- <el-icon> -->
                <!-- <Delete /> -->
            <!-- </el-icon> 删除打手</el-button> -->
        <!-- <el-button type="warning" plain> <el-icon> -->
                <!-- <Upload /> -->
            <!-- </el-icon> 批量导入</el-button> -->
    </el-card>
    <el-divider />

    <el-table :data="tableData" style="width: 100%"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" prop="sid" />
        <el-table-column label="打手ID" prop="user_id" />
        <el-table-column label="打手名" prop="user_name" />
        <el-table-column label="打手账号" prop="user_account" />
        <el-table-column label="打手密码" prop="user_password" />
        <el-table-column label="打手费用" prop="user_price" />
        <el-table-column label="创建时间" prop="user_creatime">
            <template #default="scope">
                <el-tag type="primary" v-if="scope.row.user_creatime" style="width: 100%;">
                    {{ dayjs(scope.row.user_creatime).format('YYYY-MM-DD HH:mm:ss') }}
                </el-tag>
                <el-tag type="primary" v-else style="width: 100%;">
                    {{ "-" }}
                </el-tag>
            </template>
        </el-table-column>

        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="primary" @click="handleEdit(scope.$index, scope.row)">
                    <el-icon>
                        <Edit />
                    </el-icon> 编辑
                </el-button>
                <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">
                    <el-icon>
                        <Delete />
                    </el-icon>
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-divider />
    <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]" :size="size"
        layout="->,total, sizes, prev, pager, next, jumper" :total="count" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />

    <!-- 修改学生信息对话框开始 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500" draggable>
        <el-form ref="form" :model="studentForm" label-width="100px">
            <el-form-item label="打手编号" prop="user_id">
                <el-input v-model="studentForm.user_id" :disabled="inputdisabled" />
            </el-form-item>
            <el-form-item label="打手名" prop="user_name">
                <el-input v-model="studentForm.user_name" />
            </el-form-item>
            <el-form-item label="打手账号" prop="user_account">
                <el-input v-model="studentForm.user_account" />
            </el-form-item>
            <el-form-item label="打手密码" prop="user_password">
                <el-input v-model="studentForm.user_password" />
            </el-form-item>
            <el-form-item label="打手费用" prop="user_price">
                <el-input v-model="studentForm.user_price" />
            </el-form-item>
                <!-- 开关选择器  -->
                <!-- <el-switch v-model="studentForm.gender"
                    style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" inline-prompt active-text="男"
                    inactive-text="女" active-value="男" inactive-value="女" /> -->


            <!-- <el-form-item label="联系电话" prop="telphone">
                <el-input v-model="studentForm.telphone" />
            </el-form-item>
            <el-form-item label="家庭地址" prop="address">
                <el-input v-model="studentForm.address" />
            </el-form-item> -->
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleSubmit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 修改学生信息对话框结束 -->





</template>

<style scoped></style>
